package com.yps.io.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yps
 * BIO服务端，线程池实现方式
 */
public final class ServerBetter {
	//默认端口
	private static int DEFAULT_PORT = 12344;
	//单例ServerSocket
	private static ServerSocket server;
	//线程池 懒汉加载
	private static ExecutorService executeService = Executors.newFixedThreadPool(66);
	//默认方法
	public static void start() throws IOException{
		start(DEFAULT_PORT);
	}
	public static void start(int port) throws IOException{
		if(server != null){
			return ;
		}
		try {
			//创建ServerSocket
			server = new ServerSocket(port);
			System.out.println("服务器已经启动，端口号："+port);
			//循环监听客户端连接，如果没有客户端请求，将阻塞在accept操作上
			while(true){
				Socket socket = server.accept();
				//当客户端接入时候，执行下面代码。创建一个新的线程处理并且放入线程池中
				executeService.execute(new BioServerhandler(socket));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
}
